<script setup lang="ts">
import type { LocationQueryRaw } from "vue-router";

const props = defineProps<{
  pagination: PaginationMeta;
  url?: string;
  query?: LocationQueryRaw;
}>();
const pageList = computed(() => {
  const pl = [];
  for (let i = 0; i < props.pagination.total_page; i++) {
    pl.push(i);
  }
  return pl;
});

const { page: queryPage } = useRoute().query;
const firstPage = computed(() => 0);
const lastPage = computed(() => props.pagination.total_page - 1);

const page = computed(() => {
  let p = queryPage ? parseInt(queryPage.toString(), 10) || 0 : 0;
  if (p < 0) {
    p = 0;
  }
  if (p > lastPage.value) {
    p = lastPage.value;
  }
  return p;
});
const expandedPageList = ref(false);
</script>

<template>
  <div class="relative flex justify-start items-center gap-x-2">
    <div>
      <NuxtLink
        class="border px-1 py-0.5 rounded text-sm block w-full hover:bg-gray-100"
        :to="{
          path: url || '',
          query: { ...query, page: firstPage },
        }"
        ><Icon name="uil:angle-double-left"
      /></NuxtLink>
    </div>
    <div>
      <NuxtLink
        class="border px-1 py-0.5 rounded text-sm block w-full hover:bg-gray-100"
        :to="{
          path: url || '',
          query: { ...query, page: page > firstPage ? page - 1 : 0 },
        }"
        ><Icon name="uil:angle-left"
      /></NuxtLink>
    </div>

    <div class="border px-2 py-0.5 rounded text-sm relative">
      <div
        class="flex justify-center items-center gap-x-1"
        @click="expandedPageList = !expandedPageList"
      >
        <div>{{ page + 1 }}</div>
        <Icon
          name="uil:angle-down"
          :class="{ 'rotate-180': expandedPageList }"
        />
      </div>
      <ul
        class="absolute bg-white px-3 py-1 right-0 min-w-max border shadow rounded top-6 flex-col items-start gap-y-2"
        :class="{ flex: expandedPageList, hidden: !expandedPageList }"
      >
        <li v-for="p in pageList" :key="`pagination-item-${p}`" class="">
          <NuxtLink
            :to="{
              path: url || '',
              query: { ...query, page: p },
            }"
            :class="{ 'text-cyan-600': p === page }"
            >{{ p + 1 }}</NuxtLink
          >
        </li>
      </ul>
    </div>
    <div>
      <NuxtLink
        class="border px-1 py-0.5 rounded text-sm block w-full hover:bg-gray-100"
        :to="{
          path: url || '',
          query: { ...query, page: page < lastPage ? page + 1 : lastPage },
        }"
        ><Icon name="uil:angle-right"
      /></NuxtLink>
    </div>
    <div>
      <NuxtLink
        class="border px-1 py-0.5 rounded text-sm block w-full hover:bg-gray-100"
        :to="{
          path: url || '',
          query: { ...query, page: lastPage },
        }"
        ><Icon name="uil:angle-double-right"
      /></NuxtLink>
    </div>
  </div>
</template>
